<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Ajax extends CI_Controller {

    public $render_data;

    function __construct() {
        parent::__construct();
        if (!$this->input->is_ajax_request()) {
            echo 'Bad Request!';
            //die();
        }
    }

    // Prune tmp upload cover
    function do_prune_tmp_cover() {
        $this->load->helper('directory');
        $map = directory_map('./uploads/tmp_cover/');
        $this->load->helper('file');
        // Expire Dir //
        foreach ($map as $dir => $file) {
            $dirPath = './uploads/tmp_cover/' . $dir;
            if (time() - floor($dir) >= 3600 || floor($dir) <= 0) {
                delete_files($dirPath, TRUE);
                @rmdir($dirPath);
            }
        }

        // Prune activities
        $this->db->where('actioned_at <=', time() - 604800)->delete('user_activities');
    }

    function _do_wilson($like, $view) {
        $score = (($like + 1.9208) / ($like + $view) - 1.96 * sqrt(($like * $view) /
                        ($like + $view) + 0.9604) / ($like + $view)) / (1 + 3.8416 / ($like + $view));
        $score = ($score / 2.645751311106) * 1000;
        return round($score, 4);
    }

    // Manipulate sum score
    function do_sum_score() {
        $flag = './uploads/flag/do_sum_score';
        if (!is_file($flag)) {
            fopen($flag, 'w');
        }

        // Check Time //
        $last_sum_score = filemtime($flag);

        if (time() - $last_sum_score >= 3600) {
            // List all user_activites count//
            //SELECT shop_id,count(*),sum(is_like) FROM user_activities GROUP BY shop_id
            $query = $this->db->select('shop_id,COUNT(*) as view_sum, SUM(is_like) as like_sum')
                    ->group_by('shop_id')
                    ->where('actioned_at >', time() - 604800)
                    ->get('user_activities');

            if ($query->num_rows() > 0) {
                $result = $query->result_array();
                $shop_update_data = array();
                foreach ($result as $shop) {

                    $shop_update_data[] = array(
                        'id' => $shop['shop_id'],
                        'active_wilson_score' => $this->_do_wilson($shop['like_sum'], $shop['view_sum']),
                        'active_like_score' => $shop['like_sum'],
                        'active_view_score' => $shop['view_sum']
                    );
                }
                $this->db->update_batch('shops', $shop_update_data, 'id');

                $avg_wilson_score = round($this->db->select_avg('active_wilson_score')->get('shops')->row()->active_wilson_score,4);
                
                $this->db->set('shop_level', 0)->where('active_wilson_score <', $avg_wilson_score)->update('shops');
                $this->db->set('shop_level', 1)->where('active_wilson_score >=', $avg_wilson_score)->update('shops');
                fopen($flag, 'w');
            } else {
                fopen($flag, 'w');
            }
        }
    }

    // Do Vote //
    function do_vote() {

        $shop_hash = $this->input->post('shop_hash');
        $shop_id = hashids_decrypt($shop_hash);
        if ($shop_id) {
            $this->load->library('user_agent');
            $ip_address = $this->input->ip_address();

            // Check Existing First //
            if ($this->db->where('shop_id', $shop_id)->where('ip_address', $ip_address)->where('is_like', 1)->count_all_results('user_activities') == 0) {
                $this->db->set('is_like', 1)->set('actioned_at', time())->where('shop_id', $shop_id)->where('ip_address', $ip_address)->update('user_activities');
            }
        }
    }

    function _do_view($shop_id) {
        $this->load->library('user_agent');
        $ip_address = $this->input->ip_address();

        // Check Existing First //
        if ($this->db->where('shop_id', $shop_id)->where('ip_address', $ip_address)->count_all_results('user_activities') == 0) {
            

            $data_save = array(
                'shop_id' => $shop_id,
                'ip_address' => $ip_address,
                'actioned_at' => time()
            );
            $this->db->insert('user_activities', $data_save);
        }
    }

    // Get Shop Description //
    function get_shop_description() {
        $shop_hash = $this->input->post('shop_hash');
        $shop_id = hashids_decrypt($shop_hash);
        if ($shop_id) {

            $shop = $this->db->select('shop_description')->where('id', $shop_id)->get('shops')->row_array();
            if ($shop) {
                $this->_do_view($shop_id);
                $this->load->helper('bbcode');
                echo nl2br(parse_bbcode($shop['shop_description']));
            }
        }
    }

}